package com.example.uniapp.activity.frament;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;

import com.example.uniapp.R;
import com.example.uniapp.activity.adapter.HomeCookbookListAdapter;
import com.example.uniapp.bean.CookbookBean;
import com.example.uniapp.dao.CookbookDao;

import java.util.List;

public class UserHomeFragment extends Fragment {

    View rootview; //根视图

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
        rootview = inflater.inflate(R.layout.fragment_user_home, container, false);

        //适配器
        ListView listview =rootview.findViewById(R.id.user_home_cookbook_list);
        List<CookbookBean> cookbookBeanList = CookbookDao.getAllCookbookList();
        HomeCookbookListAdapter homeCookbookListAdapter = new HomeCookbookListAdapter(getContext(), cookbookBeanList);
        if(cookbookBeanList.isEmpty()) {
            listview.setAdapter(null);
        }else {
            listview.setAdapter(homeCookbookListAdapter);
        }

        //搜索功能
        SearchView searchView = rootview.findViewById(R.id.user_home_cookbook_search);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                //根据食谱名查询食谱
                List<CookbookBean> cookbookBeanSearchList = CookbookDao.getCookbookListByName(s);
                if(cookbookBeanSearchList.isEmpty()) {
                    listview.setAdapter(null);
                }else {
                    HomeCookbookListAdapter homeCookbookListAdapter = new HomeCookbookListAdapter(getContext(), cookbookBeanSearchList);
                    listview.setAdapter(homeCookbookListAdapter);
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                //根据食谱名查询食谱
                List<CookbookBean> cookbookBeanSearchList = CookbookDao.getCookbookListByName(s);
                if(cookbookBeanSearchList.isEmpty()) {
                    listview.setAdapter(null);
                }else {
                    HomeCookbookListAdapter homeCookbookListAdapter = new HomeCookbookListAdapter(getContext(), cookbookBeanSearchList);
                    listview.setAdapter(homeCookbookListAdapter);
                }
                return false;
            }
        });
        return rootview;
    }
}